<!--标准化指标 en_standardization  standardIndex-->
<template>
    <Layout>
        <Form ref="queryForm" :model="dataToQuery" :label-width="120">
            <Row v-show="!switchFlag" class="query-form">
                <Col span="8">
                    <FormItem label="集团名称：" prop="companyId">
                        <!--<cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName' :orgTree="true" :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>-->
                        <Select class='w' placeholder="集团名称"  v-model='dataToQuery.companyId'>
                            <Option v-for="item in twoLevel" :value="item.orgId" :key="item.orgId">{{item.orgName}}</Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="年度：" prop="year" >
                        <DatePicker class="query-form-el" type="year" v-model="dataToQuery.year1" :clearable="false"
                                    @on-change="()=>{if(dataToQuery.year1 instanceof Date){dataToQuery.year = dataToQuery.year1.getFullYear().toString()}}"></DatePicker>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="reset1" class="ivu-btn-reset"  >重置</Button>
                    <Button type="primary" class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large"  class="ivu-btn-add" icon="md-add"  @click="addInfo">新增</Button>
                    <Button size="large"  class="ivu-btn-add" icon="md-download"  @click="downloadDescriptionExcel">评价指标体系模板下载</Button>
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" @on-selection-change = 'getSelectRows'
               border :columns="columns1"  :data="dataTable" >
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24" >
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>
        <Modal :title="mode ==='view'? '环境标准化指标详情':'环境标准化指标'" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow" :width=700 :styles="{height:'auto'}"  class-name='limit-height-dialog' >
            <Row>
                <Col span="24">
                    <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'modal-form'" :show-message="false" :model="dataToView" :rules="mode === 'view'?{} :ruleCustom"  :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?120:null">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="集团名称：" prop="belongOrgId">
                                    <div v-if="mode === 'view'">{{dataToView.belongOrgName}}</div>
                                    <!--<Input class="query-form-el" v-else v-model="dataToView.belongOrgName" readonly/>-->
                                    <Select v-else class='w' placeholder="集团名称"  v-model='dataToView.belongOrgId' label-in-value @on-change="belongChange">
                                        <Option v-for="item in twoLevel" :value="item.orgId" :key="item.orgId">{{item.orgName}}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="年度：" prop="yearDate" >
                                    <div v-if="mode === 'view'">{{dataToView.year}}</div>
                                    <DatePicker v-else type="year" placeholder="请输入" :clearable="false" v-model="dataToView.yearDate"></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem v-if="mode === 'view'" label="标准化指标附件：">
                                    <div v-show="dataToView.standardIdFiles.length>0" v-for="item in dataToView.standardIdFiles">
                                        <a @click="downloadFile(item)"><span style="color: #3399ff;margin-left: 5px">{{ item.fileName }}</span></a>
                                    </div>
                                </FormItem>
                                <FormItem v-else label="标准化指标附件：" prop="standardIdFiles">
                                    <div>
                                        <Upload ref="upload"
                                                :before-upload="(file) => { beforeUpload(file, 'standardId') }"
                                                :show-upload-list="true"
                                                :max-size="10240"
                                                multiple
                                                type="drag"
                                                :action="fileUrl">
                                            <div style="padding: 10px">
                                                <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                                <p>点击将文件拖拽到这里上传</p>
                                                <span style="font-size:8px;color: #797a64">支持扩展名：.xlsx </span>
                                            </div>
                                        </Upload>
                                    </div>
                                    <div v-show="dataToView.standardIdFiles.length>0" v-for="item in dataToView.standardIdFiles" :key='item'>
                                        <a @click="downloadFile(item)">{{ item.fileName }}</a>
                                        <Button type="text" icon="md-trash" @click="removeFile(item.id, 'standardId')" style="margin-left: 5px;margin-bottom: 3px"/>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem :label="mode === 'view'?'审批人：':'选择审批人：'"  prop="approvalUser">
                                    <div v-if="mode === 'view'">{{dataToView.approvalUserName }}</div>
                                    <Select v-else class='w' placeholder="审批人" type='text' v-model='dataToView.approvalUser'>
                                        <Option v-for="item in chargeList" :value="item.userId" :key="item.userId">{{item.userName}}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='填报人：' prop='createUserName'>
                                    <div v-if="mode === 'view'">{{dataToView.createUserName}}</div>
                                    <Input class="query-form-el" v-else type='text' v-model='dataToView.createUserName' readonly></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='填报人手机号：' prop='registrantPhone'>
                                    <div v-if="mode === 'view'">{{dataToView.registrantPhone}}</div>
                                    <Input class="query-form-el" v-else type='text' v-model='dataToView.registrantPhone'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='填报时间：'>
                                    <div v-if="mode === 'view'">{{renderViewDate(dataToView.createDate)}}</div>
                                    <DatePicker v-else type="date" placeholder="请选择日期" class="query-form-el" v-model='dataToView.createDate' readonly></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary" :loading="pageStatus.sending" class='ivu-btn-save' @click="submit('dialogForm')" >确定</Button>
                <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>

        <Modal :transfer=false v-model="model2" :width=500 title="审批" @on-cancel="model2=false;map={}">
            <Form ref="map" v-model="map" :rules="ruleCustom1"  :label-width="120">
                <Row class="query-form">
                    <Col span="23">
                        <FormItem label='审批结果：'>
                            <Select v-model='map.approval'>
                                <Option value="2">通过</Option>
                                <Option value="3">退回</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="23">
                        <FormItem label='审批意见：' prop="approvalNotes">
                            <Input placeholder="审批意见" type="textarea" :autosize="{minRows:2,maxRows:5}" v-model='map.approvalNotes'></Input>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save'  @click="subView(map,1)">确定</Button>
                <Button class='ivu-btn-cancel' @click="model2=false;map={}">取消</Button>
            </div>
        </Modal>

        <Modal :transfer=false v-model="model3" :width=500 title="标准指标数据导入" @on-cancel="model3=false,map={}">
            <Form :show-message="false" >
				<Row type="flex" justify="space-around" class="code-row-bg">
					<Col span="23">
						<FormItem  label="" prop="standardIdFiles">
							<div>
								<Upload ref="upload1"
										:before-upload="upload1"
										:format="['xlsx', 'xls']"
										accept=".xlsx, .xls"
										:max-size="10240"
										type="drag"
										:action="fileUrl">
									<div style="padding: 10px">
										<Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
										<p>点击将文件拖拽到这里上传</p>
										<span style="font-size:8px;color: #797a64">仅支持上传单个excel </span>
									</div>
								</Upload>
							</div>
							<div v-if="fileTrue">
								<a>{{ map.file.name }}</a>
								<Button type="text" icon="md-trash" @click="map.file = {},fileTrue = false" style="margin-left: 5px;margin-bottom: 3px"/>
							</div>
						</FormItem>
					</Col>
				</Row>
            </Form>
			<div slot="footer">
			    <Button type="primary" class='ivu-btn-save' :disabled="uploadDissabled || !fileTrue" @click="submitFile()">确定</Button>
			    <Button type="primary" class='ivu-btn-cancel' @click="model3=false,map={}">取消</Button>
			</div>
        </Modal>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    export default {
        name: "StandardIndex",
        components:{
            cascaderDom
        },
        data(){
            return{
                ...this.createCommonDataField(),
                fileUrl:Api.interestedPartiesUserFile,
                downloadUrl:Api.downloadMongoFile,
                columns1: [
                    { title: '序号', width: 70, fixed: 'left', align: 'center', render: pageCommonFunction.indexColumnsRender.bind(this)},
                    {key: 'approval', title: '审批状态', align: 'center', minWidth: 90, render: (h, params) => {
                            return h('span', {style: {color: params.row.approval=='1'?'blue':params.row.approval=='3'?'red':params.row.approval=='2'||params.row.approval=='4'?'green':'red'}},
                                params.row.approval=='1'?'待审批':params.row.approval=='3'?'审批退回':params.row.approval=='2'?'审批通过':params.row.approval=='4'?'标准指标已上传':'待提交')
                        }},
                    {title: '集团名称', align: 'center', key:'belongOrgName', minWidth: 220,},
                    {title: '年度', align: 'center', key:'year', minWidth: 90,},
                    {title: '审批人', minWidth: 120, align: 'center', key:'approvalUserName'},
                    {title: '填报人', minWidth: 100, align: 'center', key:'createUserName'},
                    {title: '填报时间', minWidth: 120, align: 'center', key:'createDate', render: this.renderCellDate},
                    {title: '审批意见', minWidth: 120, align: 'center', key:'approvalNotes', tooltip:true},
                    // this.getActionColumns()
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 250,
                        align: 'center',
                        render: (h, params) => {
                            const enable = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId ||this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                ||this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined;
                            return h('div', [
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',},
                                    on: {
                                        click: () => {
                                            this.viewData(params);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', { props: { type: 'vertical' } }, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        color: (params.row.approval==0||params.row.approval==3)&&enable?'':'#c5c8ce',
                                        pointerEvents:(params.row.approval==0||params.row.approval==3)&&enable?'':'none'},
                                    on: {
                                        click: () => {
                                            if((params.row.approval==0||params.row.approval==3)&&enable) {
                                                this.editData(params);
                                            }
                                        }
                                    }
                                }, '修改'),
                                h('Divider', { props: { type: 'vertical' } }, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        color: (params.row.approval==0||params.row.approval==3)&&enable?'red':'#c5c8ce',
                                        pointerEvents:(params.row.approval==0||params.row.approval==3)&&enable?'':'none'},
                                    on: {
                                        click: () => {
                                            if((params.row.approval==0||params.row.approval==3)&&enable) {
                                                this.deleteData(params);
                                            }
                                        }
                                    }
                                }, '删除'),
                                h('Divider', { props: { type: 'vertical' } }, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        color: (params.row.approval==0||params.row.approval==3)&&enable?'':'#c5c8ce',
                                        pointerEvents:(params.row.approval==0||params.row.approval==3)&&enable?'':'none'},
                                    on: {
                                        click: () => {
                                            if((params.row.approval==0||params.row.approval==3)&&enable) {
                                                params.row.approval=1
                                                this.subView(params.row);
                                            }
                                        }
                                    }
                                }, '提交'),
                                h('Divider', { props: { type: 'vertical' } }, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        color: params.row.approval==1&&params.row.approvalUser==this.currentUser.userId?'':'#c5c8ce',
                                        pointerEvents:params.row.approval==1&&params.row.approvalUser==this.currentUser.userId?'':'none'},
                                    on: {
                                        click: () => {
                                            if(params.row.approval==1&&params.row.approvalUser==this.currentUser.userId) {
                                                this.model2=true
                                                this.map={
                                                    approval:'2',
                                                    standardId:params.row.standardId,
                                                    createUserId:params.row.createUserId
                                                }
                                            }
                                        }
                                    }
                                }, '审批'),

                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        // color: params.row.approval==2&&enable?'':'#c5c8ce',
                                        // pointerEvents:params.row.approval==2&&enable?'':'none'
																				},
                                    on: {
                                        click: () => {
                                            // if(params.row.approval==2&&enable) {
                                                this.model3 = true
                                                this.dataToView = params.row
                                            // }
                                        }
                                    }
                                }, '导入标准指标'),
                            ]);
                        }
                    },
                ],
                ruleCustom : {
                    yearDate: [{ required: true, message: '  ', trigger: 'blur',type:'date' }],
                    belongOrgId: [{ required: true, message: '  ', trigger: 'blur' }],
                    approvalUser: [{ required: true, message: '  ', trigger: 'blur' }],
                    registrantPhone: [{
                        validator: (rule, value, callback) => {
                            if(!(/^1[3456789]\d{9}$/.test(this.dataToView.registrantPhone))){
                                callback(' ');
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blur'
                    }],
                    standardIdFiles:[{
                        validator: (rule, value, callback) => {
                            if (this.dataToView.standardIdFiles.length<1) {
                                callback('附件必须上传')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }]
                },
                ruleCustom1:{
                    // approvalNotes: [{ required: true, message: ' ', trigger: 'blur' }],
                },
                // api
                queryUrl:Api.queryStandardIndex,
                deleteUrl:Api.deleteStandardIndex,
                updateUrl:Api.updateStandardIndex,
                saveUrl:Api.saveStandardIndex,
                dictMap: {},
                model2:false,
                map:{},
				fileTrue:false,
                twoLevel:{},
                industryNames:[],
                model3:false,
                uploadDissabled: false,
                chargeList:[]
            }
        },
        mounted() {
            this.dataToQuery.year1 = new Date()
            this.dataToQuery.year = new Date().getFullYear().toString()
            this.setTableHeight();
            this.query();
            this.$http.get(Api.queryRoleUser + "/" +"17744170d3c24383bd283fbe72f3d664", {params: {}}).then((res) => {
              this.chargeList=  res.data.data
            }).catch(e => {
                this.$Message.error("数据获取失败")
            });
            this.selectSecGroupNames()
            // this.$http.get(Api.queryIndustryName, {params: {}}).then((res) => {
            //     this.industryNames = res.data.data;
            // });
        },
        methods:{
            ...pageCommonFunction,
            downloadDescriptionExcel(){
							let link = document.createElement('a');
							link.style.display = 'none';
							link.href = Api.templateDownload + '1';
							document.body.appendChild(link);
							link.click();
							document.body.removeChild(link)
                // // window.open('评价指标体系模板.xls','_blank')
                // this.$http.get(Api.templateDownload+'1', {
                //     responseType: 'blob'      //告诉服务器我们需要的响应格式
                // }).then((res) => {
                //     const aLink = document.createElement("a");
                //     let blob = new Blob([res.data], {
                //         type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                //     });
                //     aLink.href = URL.createObjectURL(blob)
                //     aLink.download = "评价指标体系模板.xlsx" //标题
                //     aLink.click()
                //     document.body.appendChild(aLink)
                // })
            },
			submitFile(){
				if (this.uploadDissabled) {
				    this.$Message.error("仅支持上传单个excel，不能重复上传");
				}else {
				    this.uploadDissabled = true
				    let formData = new FormData();
				    formData.append("file", this.map.file);
				    formData.append("standardId", this.dataToView.standardId);
				    formData.append("industryName", this.dataToView.industryName);
				    formData.append("belongOrgId", this.dataToView.belongOrgId);
				    formData.append("belongOrgName", this.dataToView.belongOrgName);
				    formData.append("createUserId", this.dataToView.createUserId);
				    formData.append("createOrgId", this.dataToView.createOrgId);
				    formData.append("year", this.dataToView.year);
				    this.$http.post(Api.uploadEnStdStandard, formData).then((res) => {
				        if (res.data.status == "200") {
				            this.$Message.success("标准信息导入成功"+res.data.data);
				            this.model3=false
				            this.dataToView={}
							this.fileTrue=false
							this.map={}
				            this.query()
				        } else {
				            this.$Message.error(res.data.data);
				        }
				        this.uploadDissabled = false
				        this.dataToView={}
						this.fileTrue=false
						this.map={}
				        this.model3=false
				    }).catch(e => {
				        console.log(e);
				        this.model3=false
				        this.dataToView={}
						this.fileTrue=false
						this.map={}
				        this.uploadDissabled = false
				        this.$Message.error("导入失败！请检查导入文档的格式是否正确");
				    })
				}
			},
            upload1(file){
				this.map = {
				   file: file
				}
				this.fileTrue = true
				return false;
            },
            selectSecGroupNames(){
                this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
                    this.twoLevel=res.data.data
                }).catch(e => {
                })
            },
            deleteData(params) {
                params.row.id=params.row.standardId
                this.deleteDateAjax(params);
            },
            belongChange(value) {
                this.dataToView.belongOrgId = value.value
                this.dataToView.belongOrgName = value.label
            },
            reset1(){
                this.dataToQuery = {
                    year1: new Date(),
                    year : new Date().getFullYear().toString()
                };
                this.pagedata.currentPage=1
                this.query()
            },
            query() {
                this.dataToQuery.userId=this.currentUser.userId,
                this.queryAjax()
            },
            submit(name) {
                if(this.dataToView.yearDate) {
                    this.dataToView.year = this.dataToView.yearDate.getFullYear();
                }
                this.submitAjax(name);
            },
            subView(row,type){
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>是否要提交？</p>',
                    onOk: () => {
                        this.$http.put(this.updateUrl, row).then((res) => {
                            this.$Message.info('提交成功')
                            this.query()
                            this.model2=false
                            })
                    },
                    onCancel: () => {
                        this.query()
                        this.model2=false
                    }
                });
            },
            createEmptyDataToAdd() {
                return {
                    standardId:this.get_uuid(),
                    standardIdFiles:[],
                    createDate:new Date(),
                    yearDate:new Date(),
                    approval:0,
                    createUserName:this.currentUser.userName
                }
            },
            async beforeEditDialogOpen(data) {
                data.row.yearDate = new Date(data.row.year + '-01-01');
            },
            async afterDataToViewInit() {
                await this.getFiles('standardId');
            }
        },
        watch:{
        },

    }
</script>

<style lang='css' scoped>
    .ivu-form-item {
        padding-right: 20px;
    }

    .query-form-el, .ivu-date-picker, .ivu-input-wrapper {
        width: 100%;
    }
</style>
